package com.zyf.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyf.pojo.SmbmsUser;
import com.zyf.service.SmbmsUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义Realm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    SmbmsUserService service;

    //认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*//拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        SmbmsUser currentUser = (SmbmsUser) subject.getPrincipal(); //拿到User对象
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());*/
        return info;
    }



    //授权
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //用户名、密码，数据库中取
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        QueryWrapper<SmbmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("loginname",userToken.getUsername());
        SmbmsUser login = service.getOne(wrapper);

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("uName",login);

        if(login==null){ //没有这个人
            return null;
        }

        //密码认证，shiro做

        return new SimpleAuthenticationInfo(login,login.getLoginpwd(),"");
    }
}


